package ruleengine

import (
	"encoding/json"
	"go-iot/app/common/logger"
	"go-iot/app/iot/notify"
)

type NotifierAction struct {
	NotifyType string                 `json:"notifyType"`
	NotifierId int64                  `json:"notifierId"`
	NotifyMode string                 `json:"notifyMode"`
	Data       map[string]interface{} `json:"-"`
}

func NewNotifierAction(config string, data map[string]interface{}) (*NotifierAction, error) {
	action := &NotifierAction{}
	err := action.FromJson(config)
	if err != nil {
		return nil, err
	}
	action.Data = data
	return action, nil
}

func (action *NotifierAction) FromJson(str string) error {
	err := json.Unmarshal([]byte(str), &action)
	return err
}

func (action *NotifierAction) Send() {
	notify := notify.GetNotify(action.NotifierId)
	if notify == nil {
		logger.Warnf("通知配置未找到 id=%d, 类型=%s", action.NotifierId, action.NotifyType)
		return
	}

	var templateData map[string]interface{}
	if action.NotifyMode == "simple" {
		templateData = action.Data
		if action.Data["data"] != nil {
			dataArray := action.Data["data"].([]map[string]interface{})
			newData := make(map[string]interface{})
			for _, item := range dataArray {
				name := item["name"].(string)
				newData[name] = item["value"]
			}
			templateData["data"] = newData
		}
	} else {
		templateData = action.Data
	}

	err := notify.Notify(notify.ParseTemplate(templateData))
	if err != nil {
		logger.Warnf("发送通知失败: %v", err)
	}
}
